<template>
  <div>
    <div class="all">
      <!-- 搜索框 -->
      <div class="search_box">
        <div class="search_left">
          <div class="search_title">用户名称</div>
          <div>
            <el-input v-model="searchParams.name" class="seek" placeholder="请输入用户名称" @input="debouncedSearch" />
          </div>
        </div>
        <div>
          <div class="search_title">商品名称</div>
          <div>
            <el-input v-model="searchParams.title" class="seek" placeholder="请输入商品名称" @input="debouncedSearch" />
          </div>
        </div>
        <div class="search_righ">
          <div class="search_title">创建时间</div>
          <div>
            <el-date-picker v-model="searchParams.dateRange" type="daterange" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" size="default" @change="debouncedSearch" />
          </div>
        </div>
      </div>
      <div class="line"></div>
      <div class="button_box">
        <el-button type="primary" class="butten" @click="exportData">导出</el-button>
        <div class="search_righ">
          <el-button size="default" class="butten" @click="filterByStatus('all')">全部</el-button>
          <el-badge :value="pendingCount" :max="99" class="butten">
            <el-button size="default" @click="filterByStatus(1)">待兑换</el-button>
          </el-badge>
          <el-badge :value="exchangedCount" :max="99" class="butten">
            <el-button size="default" @click="filterByStatus(2)">已兑换</el-button>
          </el-badge>
        </div>
      </div>
      <div class="table_box">
        <el-table :data="paginatedData" @selection-change="handleSelectionChange" v-loading="loading">
          <el-table-column type="selection" width="55" />
          <el-table-column label="id" width="120" align="center">
            <template #default="scope">{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column property="name" label="用户名称" width="200" align="center" show-overflow-tooltip />
          <el-table-column property="title" label="商品名称" align="center" show-overflow-tooltip />
          <el-table-column property="num" label="总数量" align="center" show-overflow-tooltip />
          <el-table-column property="price" label="总价格" align="center" show-overflow-tooltip />

          <el-table-column label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.status == 2" type="primary">已兑换</el-tag>
              <el-tag v-if="row.status === 1" type="warning">未兑换</el-tag>
            </template>
          </el-table-column>
          <el-table-column property="createtime" label="购买时间" align="center" />
          <el-table-column property="address" label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" disabled text>审核</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, reactive } from 'vue'
import "/src/css/business.css";
import { historyList } from '/@/api/score/score_history';

// 定义数据类型
interface DataItem {
  id: number;
  name: string;
  title: string;
  status: number;
  num: number;
  price: number;
  createtime: string;
  address: string;
}

// 搜索参数
const searchParams = reactive({
  name: '',
  title: '',
  dateRange: [] as Date[],
  status: 'all' as 'all' | 1 | 2
});

// 响应式数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const allData = ref<DataItem[]>([]);
const filteredData = ref<DataItem[]>([]);
const paginatedData = ref<DataItem[]>([]);
const loading = ref(false);
const selectedRows = ref<DataItem[]>([])
// 基础筛选数据（仅考虑名称、商品、时间范围，不考虑状态）
const baseFilteredData = computed(() => {
  return allData.value.filter(item => {
    const nameMatch = item.name.toLowerCase().includes(searchParams.name.toLowerCase());
    const titleMatch = item.title ? item.title.toLowerCase().includes(searchParams.title.toLowerCase()) : true;

    let timeMatch = true;
    if (searchParams.dateRange.length === 2) {
      const createTime = new Date(item.createtime).getTime();
      const start = searchParams.dateRange[0].getTime();
      const end = searchParams.dateRange[1].getTime() + 86400000 - 1; // 包含结束日整天
      timeMatch = createTime >= start && createTime <= end;
    }

    return nameMatch && titleMatch && timeMatch;
  });
});

// 角标数字基于基础筛选数据计算（忽略状态筛选）
const pendingCount = computed(() => {
  return baseFilteredData.value.filter(item => item.status === 1).length;
});

const exchangedCount = computed(() => {
  return baseFilteredData.value.filter(item => item.status === 2).length;
});

// 编辑操作
const edit = (row: DataItem) => {
  console.log('编辑数据:', row);
};

// 选择项变化
const handleSelectionChange = (selection: DataItem[]) => {
  selectedRows.value = selection;
};

// 分页尺寸变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  updatePaginatedData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  updatePaginatedData();
};

// 状态筛选
const filterByStatus = (status: 'all' | 1 | 2) => {
  searchParams.status = status;
  currentPage.value = 1;
  debouncedSearch();
};

// 更新筛选数据（包含状态筛选）
const updateFilteredData = () => {
  filteredData.value = baseFilteredData.value.filter(item => {
    if (searchParams.status !== 'all') {
      return item.status === searchParams.status;
    }
    return true;
  });

  total.value = filteredData.value.length;
  updatePaginatedData();
};

// 更新分页数据
const updatePaginatedData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  paginatedData.value = filteredData.value.slice(start, end);
};

// 防抖函数
const debounce = <T extends (...args: any[]) => void>(fn: T, delay: number) => {
  let timer: NodeJS.Timeout | null = null;
  return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
};

// 搜索处理
const search = () => {
  currentPage.value = 1;
  updateFilteredData();
};

const debouncedSearch = debounce(search, 300);

// 导出数据
const exportData = () => {
  console.log('导出筛选后的数据:', filteredData.value);
};

// 获取数据
const fetchData = () => {
  loading.value = true;
  historyList()
    .then((res) => {
      const list = res.data.list || res.data;
      allData.value = list.map((item: any) => ({
        ...item,
        status: Number(item.status) // 确保状态为数字类型
      }));
      updateFilteredData();
    })
    .catch(error => {
      console.error('获取数据失败:', error);
      allData.value = [];
      filteredData.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
};

// 监听搜索参数变化
watch([
  () => searchParams.name,
  () => searchParams.title,
  () => searchParams.dateRange,
  () => searchParams.status
], () => {
  debouncedSearch();
}, { deep: true });

// 监听原始数据变化
watch(allData, () => {
  updateFilteredData();
}, { deep: true });

// 初始化加载
onMounted(() => {
  fetchData();
});
</script>

<style scoped></style>